package com.itcast.spring6.ioc.bean;

import cn.hutool.json.JSONUtil;
import com.itcast.spring6.ioc.application_context.User;
import com.itcast.spring6.ioc.bean.anno.UserGroup1;
import com.itcast.spring6.ioc.bean.anno.UserGroup2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**
 * Qualifier的分组功能
 * @author zhangtian105
 * @date 2023/4/28
 * @apiNote
 */
@Slf4j
public class QualifierGroupTest {
    @Autowired
    @Qualifier
    private Collection<User> allUser ;

    @Autowired
    @UserGroup1
    private Collection<User> group1User ;

    @Autowired
    @UserGroup2
    private Collection<User> group2User ;

    public static void main(String[] args) {
        // 创建容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext() ;
        // 注册Configuration Class（配置类）
        applicationContext.register(QualifierGroupTest.class);
        // 启动应用上下文
        applicationContext.refresh();

        QualifierGroupTest qualifierGroupTest = applicationContext.getBean(QualifierGroupTest.class) ;
        log.info("QualifierGroupTest allUser is: {}", JSONUtil.toJsonStr(qualifierGroupTest.allUser));
        log.info("QualifierGroupTest group1User is: {}", JSONUtil.toJsonStr(qualifierGroupTest.group1User));
        log.info("QualifierGroupTest group2User is: {}", JSONUtil.toJsonStr(qualifierGroupTest.group2User));

        // 关闭spring应用上下文
        applicationContext.close();
    }

    @Bean
    @UserGroup1
    public User user1() {
        return User.builder().name("user1").age(1).build() ;
    }

    @Bean
    @UserGroup1
    public User user2() {
        return User.builder().name("user2").age(2).build() ;
    }

    @Bean
    @UserGroup2
    public User user3() {
        return User.builder().name("user3").age(3).build() ;
    }

    @Bean
    @UserGroup2
    public User user4() {
        return User.builder().name("user1").age(4).build() ;
    }
}
